<?php
/**
 * *
 *  * ============================================================================
 *  * Created by PhpStorm.
 *  * User: Ice
 *  * 邮箱: ice@sbing.vip
 *  * 网址: https://sbing.vip
 *  * Date: 2019/9/19 下午4:21
 *  * ============================================================================.
 */

namespace app\common\library;

use app\common\controller\MessageCommon;
use think\facade\Event;
use think\facade\Db;
use app\common\library\AliSms as AliSmslib;
/**
 * 短信验证码类.
 */
class Sms
{
    /**
     * 验证码有效时长
     *
     * @var int
     */
    protected static $expire = 180;

    /**
     * 最大允许检测的次数.
     *
     * @var int
     */
    protected static $maxCheckNums = 10;

    /**
     * 获取最后一次手机发送的数据.
     *
     * @param int    $mobile 手机号
     * @param string $event  事件
     *
     * @return Sms
     */
    public static function get($mobile, $event = 'default')
    {
        $sms = \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        return $sms ? $sms : null;
    }

    /**
     * 发送验证码
     *
     * @param int    $mobile 手机号
     * @param int    $code   验证码,为空时将自动生成4位数字
     * @param int    $type   类型 1登录 2取货码 3无人接单 4骑手通过审核
     * @param string $event  事件
     *
     * @return bool
     */
    public static function send($mobile, $code = null, $order_title = null, $type = 1, $event = 'default')
    {
		$code = is_null($code) ? mt_rand(100000, 999999) : $code;
		$mesage = new MessageCommon();
        switch ($type){
			case 11;
			    $content = '您的会员服务已生效，可进入健康管家会员中心查看并使用服务，如有疑问详询4001088679';					
			    break;
        }
		$data['mobile'] = $mobile;
		$data['content'] = $content;
		//现在只有1和8
		if($type == 11){
			//发送营销短信
			$data = [
			    'phone'=> $mobile,
			    'template' => config('app.aliyun.lnSms'),
			    'name' => config('app.aliyun.lnSmsName'),
			    // 'info' => ['code'=>$code]  //根据模板里面的变量来填写
			];
			//调用阿里云短信发送方法
			$send = new AliSmslib;
			$result = $send::main($data,$type);
			// $result = $mesage->singleSend($data,1);
		}else{
			$result = $mesage->singleSend($data,1);
		}
		$re['event'] = $event;
		$re['mobile'] = $mobile;
		$re['code'] = $code;
		$re['type'] = $type;
		$re['ip'] = request()->ip();
		$re['coupon_code_psd'] = $order_title;
		$re['content'] = json_encode($result);
		$re['createtime'] = time();
		$re['status'] = $result['result'];
		Db::name('error_log')->insert($re);
		// $result['result'] = 0;
		if ($result['result'] == 0){
			$time = time();
			$ip = request()->ip();
			// if($event == 'default'){
			// 	//发送成功之后把卡密改成已发送 如果是给用户发送卡密和网址的
			// 	$da['is_send'] = 2;
			// 	$da['mobile'] = $mobile;
			// 	Db::name('cdkey')->where('is_del',1)->where('coupon_code_psd',$code)->update($da);
			// }
			$sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
			if (! $sms) {
				$sms->delete();
				return false;
			}

			return true;
		}else{
			//报警后台查看订单情况
			$pars['title'] = '接口异常';
			$pars['content'] = '北京移动短信接口异常'.$result['message'];
			request_post('http://cladmin.xinquanyu.top/index.php/api/Apimobile/sendDing',json_encode($pars));
			return false;
		}
	}
    /**
     * 发送通知.
     *
     * @param mixed  $mobile   手机号,多个以,分隔
     * @param string $msg      消息内容
     * @param string $template 消息模板
     * @param array  $data     模板变量
     *
     * @return bool
     */
    public static function notice($mobile, $msg = '', $template = null, $data = [])
    {
        $params = [
            'mobile'   => $mobile,
            'msg'      => $msg,
            'template' => $template,
            'data'     => $data,
        ];
        $result = Event::trigger('sms_notice', $params, true);

        return $result ? true : false;
    }

    /**
     * 校验验证码
     *
     * @param int    $mobile 手机号
     * @param int    $code   验证码
     * @param string $event  事件
     *
     * @return bool
     */
    public static function check($mobile, $code, $event = 'default')
    {
        // if($code != 'qwas'){
            $time = time() - self::$expire;
            $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
                ->order('id', 'DESC')
                ->find();
            if ($sms) {
                if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums) {
                    $correct = $code == $sms['code'];
                    if (! $correct) {
                        $sms->times = $sms->times + 1;
                        $sms->save();
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    // 过期则清空该手机验证码
//                    self::flush($mobile, $event);
                    return false;
                }
            } else {
                return false;
            }
        // }
        // return true;
    }

    /**
     * 清空指定手机号验证码
     *
     * @param int    $mobile 手机号
     * @param string $event  事件
     *
     * @return bool
     */
    public static function flush($mobile, $event = 'default')
    {
        \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->delete();
        return true;
    }
}
